package cn.doitedu.engine;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ArrayBlockingQueue;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.googlecode.aviator.AviatorEvaluator;
import com.googlecode.aviator.Expression;

public class CalculatorRunnable implements Runnable{

    HashMap<String, String> rules;
    ArrayBlockingQueue<String> dataQueue;

    public CalculatorRunnable() throws IOException, ClassNotFoundException {
        this.dataQueue = StaticContextV2.getDataQueue();
        this.rules = StaticContextV2.getOrRestoreRuleMap();

//        this.rules = StaticContext.ruleMap;
//        this.dataQueue = StaticContext.dataQueue;
    }


    @Override
    public void run() {

        while(true){
            try {

                // 拉取一条行为json日志数据
                // {"user_id":1,"event_id":"rate","properties":{"f1":80.2,"f2":90.5,"f3":86.8}}
                String json = dataQueue.take();
                // 解析json
                JSONObject jsonObject = JSON.parseObject(json);
                int userId = jsonObject.getIntValue("user_id");
                String eventId = jsonObject.getString("event_id");
                JSONObject propertiesObject = jsonObject.getJSONObject("properties");
                float f1 = propertiesObject.getFloatValue("f1");
                float f2 = propertiesObject.getFloatValue("f2");
                float f3 = propertiesObject.getFloatValue("f3");

                // 准备表达式计算要用的数据
                HashMap<String, Object> expressionParams = new HashMap<>();
                expressionParams.put("f1",f1);
                expressionParams.put("f2",f2);
                expressionParams.put("f3",f3);


                // 遍历规则容器中的每一个规则
                for (Map.Entry<String, String> entry : rules.entrySet()) {

                    String ruleId = entry.getKey();

                    // "f1+f2+f3"
                    String expStr = entry.getValue();

                    // 编译表达式
                    Expression expression = AviatorEvaluator.compile(expStr);

                    // 执行表达式
                    Object result = expression.execute(expressionParams);

                    // 拼装输出结果
                    JSONObject resultObject = new JSONObject();
                    resultObject.put("user_id",userId);
                    resultObject.put("event_id",eventId);
                    resultObject.put("rule_id",ruleId);
                    resultObject.put("result",result);


                    System.out.println(resultObject.toJSONString());

                }

            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }

        }




    }
}
